<template>
  <el-card class="page-card">
    <h2>站内信列表</h2>
    <!-- 搜索栏 -->
    <el-form :inline="true" :model="query" class="filter-form" @submit.prevent>
      <el-form-item label="标题">
        <el-input v-model="query.title" placeholder="标题关键词" clearable />
      </el-form-item>
      <el-form-item label="类型">
        <el-select v-model="query.type" placeholder="全部" clearable style="width: 160px">
          <el-option v-for="(label, val) in typeMap" :key="val" :label="label" :value="val" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="fetchList()">搜索</el-button>
        <el-button @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 工具栏 -->
    <div class="toolbar">
      <el-button type="primary" @click="openCreate">新增通知</el-button>
    </div>

    <!-- 表格 -->
    <el-table :data="list" border stripe height="520">
      <el-table-column type="index" width="60" label="#" />
      <el-table-column prop="id" label="ID" width="90" />
      <el-table-column prop="title" label="标题" show-overflow-tooltip />
      <el-table-column prop="type" label="类型" width="120">
        <template #default="{ row }">{{ typeMap[row.type] || row.type }}</template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="180" />
      <el-table-column prop="updateTime" label="更新时间" width="180" />
      <el-table-column label="操作" width="220" fixed="right">
        <template #default="{ row }">
          <el-button size="small" @click="openEdit(row)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        v-model:page-size="pageSize"
        v-model:current-page="pageNum"
        :page-sizes="[10, 20, 50, 100]"
        @current-change="fetchList"
        @size-change="fetchList"
      />
    </div>
  </el-card>

  <!-- 新增 / 编辑 弹窗 -->
  <el-dialog v-model="dialog.visible" :title="dialog.isEdit ? '编辑通知' : '新增通知'" width="640px" destroy-on-close>
    <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
      <el-form-item label="标题" prop="title">
        <el-input v-model="form.title" maxlength="200" show-word-limit />
      </el-form-item>

      <el-form-item label="类型" prop="type">
        <el-select v-model="form.type" placeholder="请选择类型" style="width: 200px">
          <el-option v-for="(label, val) in typeMap" :key="val" :label="label" :value="val" />
        </el-select>
      </el-form-item>

      <el-form-item label="内容" prop="content">
        <el-input
          v-model="form.content"
          type="textarea"
          :rows="6"
          placeholder="支持 Markdown / HTML"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="dialog.visible = false">取 消</el-button>
      <el-button type="primary" @click="submitForm">确 定</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  getNoticeList,
  addNotice,
  editNotice,
  deleteNotice
} from '@/api/notice'

/** 类型映射 */
const typeMap = {
  1: '新闻',
  2: '降价通知',
  3: '其它'
}

/* ---------- 列表与分页 ---------- */
const query = reactive({ title: '', type: null })
const pageNum = ref(1)
const pageSize = ref(10)
const total = ref(0)
const list = ref([])

const fetchList = async () => {
  try {
    const res = await getNoticeList(pageNum.value, pageSize.value, query)
    const data = res.data.data  
    console.log(res,"站内信")        // PageDTO
    list.value = data.list
    total.value = data.list.length
  } catch (e) {
    console.log(e)
    ElMessage.error('加载失败')
  }
}

const resetQuery = () => {
  query.title = ''
  query.type = null
  pageNum.value = 1
  fetchList()
}

/* ---------- 弹窗 & 表单 ---------- */
const dialog = reactive({ visible: false, isEdit: false })
const form = reactive({
  id: null,
  title: '',
  content: '',
  type: null
})
const formRef = ref(null)

const rules = {
  title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
  content: [{ required: true, message: '请输入内容', trigger: 'blur' }],
  type: [{ required: true, message: '请选择类型', trigger: 'change' }]
}

const openCreate = () => {
  dialog.isEdit = false
  dialog.visible = true
  Object.assign(form, { id: null, title: '', content: '', type: null })
}

const openEdit = (row) => {
  dialog.isEdit = true
  dialog.visible = true
  Object.assign(form, row)      // id/title/content/type
}

const submitForm = () => {
  formRef.value.validate(async (valid) => {
    if (!valid) return
    try {
      if (dialog.isEdit) {
        await editNotice(form)
        ElMessage.success('编辑成功')
      } else {
        await addNotice(form)
        ElMessage.success('新增成功')
      }
      dialog.visible = false
      fetchList()
    } catch (e) {
      ElMessage.error(e.response?.data?.message || '操作失败')
    }
  })
}

/* ---------- 删除 ---------- */
const handleDelete = (row) => {
  ElMessageBox.confirm(`确认删除【${row.title}】吗？`, '提示', { type: 'warning' })
    .then(async () => {
      await deleteNotice(row.id)
      ElMessage.success('删除成功')
      // 若当前页只剩一条被删了，自动回退一页
      if (list.value.length === 1 && pageNum.value > 1) pageNum.value--
      fetchList()
    })
    .catch(() => {}) // 用户取消
}

onMounted(fetchList)
</script>

<style scoped>
.page-card {
  height: 100%;
  display: flex;
  flex-direction: column;
}
.filter-form {
  margin-bottom: 10px;
}
.toolbar {
  margin-bottom: 10px;
}
.pagination {
  margin-top: 12px;
  text-align: right;
}
</style>
